using Microsoft.Extensions.DependencyInjection;
using Microsoft.Win32;
using Models;
using Newtonsoft.Json;
using Services;
using System.IO;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using UserControls.CustControls;
using Utils;
using WorkPieceDataCapture;
using WorkPieceDataCapture.ViewModels;

namespace ViewModels
{
    public class vm_Search_PointCheck : vm_Base
    {
        #region 全局变量与枚举
        private IServiceProvider _serviceProvider;
        WorkPieceDataCaptureRespository respository;
        List<PointCheckRecord>? _list_History;
        model_SearchCondition_PointCheck? _conditions { get; set; }
        public model_SearchCondition_PointCheck? Conditions
        {
            get { return _conditions; }
            set
            {
                _conditions = value;
                OnPropertyChanged(nameof(Conditions));
            }
        }
        public List<PointCheckRecord>? list_History
        {
            get { return _list_History; }
            set
            {
                _list_History = value;
                OnPropertyChanged(nameof(list_History));
            }
        } //查询结果
        SearchSummary _searchSummary;
        public SearchSummary searchSummary
        {
            get { return _searchSummary; }
            set
            {
                _searchSummary = value;
                OnPropertyChanged(nameof(searchSummary));
            }
        } //查询结果统计
        #endregion
        #region 事件注册
        public ICommand doSearchCommand { get; set; }   //执行查询事件
        public ICommand doExportListCommand { get; set; } //执行导出列表数据的事件
        public ICommand SelectDateCommand { get; set; } //选择日期的事件
        #endregion
        #region 构造与析构函数
        /// <summary>
        /// 构造函数
        /// </summary>
        public vm_Search_PointCheck(IServiceProvider serviceProvider)
        {
            this._serviceProvider = serviceProvider;
            this.respository = new WorkPieceDataCaptureRespository(this._serviceProvider);
            doSearchCommand = new RelayCommand(doSearch);   //点击查询按钮的事件注册
            doExportListCommand = new RelayCommand(doExportList);   //执行导出列表的事件注册
            SelectDateCommand = new RelayCommand(SelectDate);   //选择日期的事件注册
            this._conditions = new model_SearchCondition_PointCheck();
            this._conditions.CheckTime_End = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, 23, 59, 59);
            this._conditions.CheckTime_Begin = this._conditions.CheckTime_End.Value.AddDays(-7).AddSeconds(1);
        }
        /// <summary>
        /// 析构函数
        /// </summary>
        ~vm_Search_PointCheck()
        {

        }
        #endregion
        #region 事件
        /// <summary>
        /// 执行数据查询
        /// </summary>
        /// <param name="parameter"></param>
        private void doSearch(object parameter)
        {
            try
            {
                var context = this._serviceProvider.GetService<AppDbContext>();
                if (context != null)
                {
                    if (Conditions.CheckTime_Begin > Conditions.CheckTime_End)
                    {
                        MessageBox.Show("开始日期不能大于结束日期！");
                        return;
                    }
                    var list_Final = new List<tb_PointCheckRecord>();    //存放最终结果
                    var list_FinalJson = new List<string>();    //存放不同实体类但是相同结构的数据的json
                    #region 如果查询的年月区间包含一个月以内的数据，则需要从实时表里查询数据
                    var nowYearMonth = DateTime.Now.ToString("yyyyMM");
                    var result_RealTime = this.respository.SearchDataFromPointCheckTable(Conditions, context.tb_PointCheckRecord);
                    if (result_RealTime.bSuccess)
                    {
                        if (result_RealTime.obj_Return.Count > 0)
                        {
                            list_Final.AddRange(result_RealTime.obj_Return);
                        }
                    }
                    else
                    {
                        MessageBox.Show("从实时数据表中获取数据时出现错误！" + result_RealTime.strMsg);
                        return;
                    }
                    #endregion
                    list_FinalJson.ForEach(ee =>
                    {
                        list_Final.Add(JsonConvert.DeserializeObject<tb_PointCheckRecord>(ee));
                    });
                    int increment = 1;
                    foreach (var item in list_Final)
                    {
                        item.iID = increment++;
                    }
                    list_History = list_Final.Select(x => x.TransToDomainModel().Result).ToList();
                    if (list_History.Count > 0)
                    {
                        var Summary = new SearchSummary();
                        Summary.RecordCount = list_Final.Count;
                        this.searchSummary = Summary;
                    }
                    else
                    {
                        this.searchSummary = new SearchSummary();
                    }
                }
                else
                {
                    MessageBox.Show("当前无法连接到数据库，请重试一次");
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("执行查询操作发生异常！\n" + ex.Message);
            }
        }
        /// <summary>
        /// 执行导出列表数据
        /// </summary>
        /// <param name="parameter"></param>
        private void doExportList(object parameter)
        {
            if (this.list_History == null || this.list_History.Count == 0) return;
            string strNewFileName = "";
            try
            {
                //将模板文件复制一份
                strNewFileName = AppDomain.CurrentDomain.BaseDirectory + "Files\\" + Guid.NewGuid().ToString().Replace("-", "") + ".xlsx";
                File.Copy(AppDomain.CurrentDomain.BaseDirectory + "Files\\ExportListTemplate_PointCheck.xlsx", strNewFileName);
            }
            catch (Exception ex)
            {
                MessageBox.Show("复制模板到新文件出错！\n" + ex.Message);
                return;
            }
            try
            {
                var helper = new ExcelHelper();
                helper.WriteEntityListToExcel(this.list_History, strNewFileName, "Sheet1", GlobalClass.dic_ExportColumnRelation_PointCheck, 1);
            }
            catch (Exception ex)
            {
                MessageBox.Show("导出文件到Excel出错！\n" + ex.Message);
                return;
            }
            try
            {
                SaveFileDialog dialog = new SaveFileDialog();
                if (dialog.ShowDialog() == true)
                {
                    if (!dialog.FileName.Contains(".xlsx"))
                    {
                        File.Move(strNewFileName, dialog.FileName + ".xlsx");
                    }
                    else
                    {
                        File.Move(strNewFileName, dialog.FileName);
                    }
                    MessageBox.Show("导出成功");
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("将导出的Excel移动到目标文件夹出错！\n" + ex.Message);
                return;
            }
        }
        private void SelectDate(object parameter)
        {
            var txt = parameter as TextBox;
            DateTimePicker dialog = new DateTimePicker();
            dialog.ShowDialog();
            if (dialog.DialogResult == true)
            {
                switch (txt.Name)
                {
                    case "txtDate_Begin":
                        this._conditions.CheckTime_Begin = DateTime.Parse(dialog.strSelectedDateTime);
                        break;
                    case "txtDate_End":
                        this._conditions.CheckTime_End = DateTime.Parse(dialog.strSelectedDateTime);
                        break;
                }
            }
        }
        #endregion
        #region 方法

        #endregion
    }
}
